<!-- 流程审批页面 -->
<template>
  <div v-if="approvePageShow">
    <component :is="approvePage" :approveObject="approveObjectClone" :buttons="buttons" @close="close"></component>
  </div>
  <div v-else>
    <component v-if="approveIframeShow" ref="approveIFrame" :is="approveIframePage" :approveObject="approveObjectClone" :buttons="buttons" @close="close"></component>
    <div class="empty"></div>
    <el-form label-width="100px">
      <el-form-item label="审批节点：">
        <span>{{ approveObjectClone.taskName }}</span>
      </el-form-item>
      <el-form-item label="审批意见：">
        <el-input v-model="approveContent" type="textarea" />
      </el-form-item>
      <el-form-item label="抄送：">
        <el-input
            v-model="ccUserId"
            style="width: 120px"
            disabled
        />
        <el-button type="primary" @click="handleSelectCCUser">选择</el-button>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <div class="dialog-footer">
      <el-button @click="handle(button.click, approveObjectClone.taskId)" v-for="(button, index) in buttons" :key="index" :type="button.type">{{ buttonRename(button) }} </el-button>
    </div>
    <select-next-user :visible="selectUserOpen" :selectUserParam="selectUserParam" @selected="doSelected" @close="selectUserOpen = false"></select-next-user>
    <OrgPicker ref="orgPicker" @ok="doSelectedOrg"></OrgPicker>

    <!--可驳回的列表-->
    <el-dialog v-model="rejectedNodesOpen" title="可驳回的节点" width="50%" @close="closeNodeSelectDialog()">
      <el-radio-group v-model="rejectedNode">
        <el-radio v-for="node in rejectedNodeList" :key="node.taskId" :label="node.taskId" border>
          {{ node.taskName }} - 审批人：{{ node.params.userName }}
        </el-radio>
      </el-radio-group>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeNodeSelectDialog()">取 消</el-button>
          <el-button type="primary" @click="confirmSelection()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getWfButton } from './api';
import SelectNextUser from './SelectNextUser.vue';
import OrgPicker from '@/components/Zmids/OrgPicker/index.vue';
import { useAnvilCodeStore } from '@code/components/anvil-code-low-common/store/modules/code';
import { getRejectedEnableNodes } from '@/platform/wf/api/wf/common/zbiti-wf.js';

export default {
  name: 'WfApprove',
  components: { OrgPicker, SelectNextUser },
  props: {
    approveObject: {
      type: Object,
      require: true
    }
  },
  data() {
    return {
      // 整个审批页面
      approvePage: {},
      // 显示整个审批页面
      approvePageShow: false,
      // 审批内嵌页面
      approveIframePage: {},
      // 审批嵌入页面是否加载
      approveIframeShow: true,
      //审批内容
      approveContent: '',
      // 审批按钮
      buttons: [],
      // 选择下一步处理人窗口
      selectUserOpen: false,
      // 选择下一步处理参数
      selectUserParam: {},
      // approveObject对象的拷贝
      approveObjectClone: null,
      // 可驳回的节点列表
      rejectedNodeList: null,
      // 可驳回的节点列表弹窗
      rejectedNodesOpen: false,
      // 驳回节点
      rejectedNode: null,
      // 驳回到指定节点的参数
      rejectedNodeParam: {},
      taskId: '',
      // 抄送人
      ccUserId: '',
    };
  },
  watch: {
    // 绑定父页面审批对象的改变
    approveObject(newVal, oldVal) {
      // 重新初始化
      this.initData();
      this.updateDataFromProp();
    }
  },
  created() {
    //初始化
    this.initData();
    // 从属性中初始化数据
    this.updateDataFromProp();
  },
  methods: {
    // 初始化数据
    initData() {
      // 整个审批页面
      this.approvePage = {};
      // 显示整个审批页面
      this.approvePageShow = false;
      // 审批内嵌页面
      this.approveIframePage = {};
      // 审批嵌入页面是否加载
      this.approveIframeShow = true;
      //审批内容
      this.approveContent = '';
      // 审批按钮
      this.buttons = [];
      // 选择下一步处理人窗口
      this.selectUserOpen = false;
      // 选择下一步处理参数
      this.selectUserParam = {};
      // 获取对象拷贝
      this.approveObjectClone = this.approveObject;
    },
    // 从属性中更新数据
    async updateDataFromProp() {
      // 存在输入参数
      if (this.approveObjectClone != null) {
        // 整个审批页面
        const approveUrl = this.approveObjectClone.approveUrl;
        // 通用审批页面的内嵌Iframe
        const approveFrameUrl = this.approveObjectClone.approveFrameUrl;

        // 是否显示整个审批页面
        this.approvePageShow = approveUrl != null && approveUrl.length > 0;
        if (this.approvePageShow) {
          // 存在审批页面配置，接管整个审批页面
          // 路径由anvil-code-low-common开头则由低代码渲染页面接管,格式为'/anvil-code-low-common/views/page/filling/flowFilling/:pageId'
          if (approveUrl.startsWith('/anvil-code-low-common')) {
            const pageIdIndex = approveUrl.lastIndexOf('/');
            const pageId = approveUrl.substring(pageIdIndex + 1);
            const filling = approveUrl.substring(0, pageIdIndex);
            this.approveObjectClone.pageId = pageId;
            const module = await import(`/@/platform/code/components${filling}.vue`);
            this.approvePage = module.default;
          } else {
            const module = await import(`/@/views${approveUrl}.vue`);
            this.approvePage = module.default;
          }
        } else {
          // 是否显示Iframe内嵌页面配置
          this.approveIframeShow = approveFrameUrl != null && approveFrameUrl.length > 0;
          if (this.approveIframeShow) {
            // 路径由anvil-code-low-common开头则由低代码渲染页面接管,格式为'/anvil-code-low-common/views/page/filling/flowFilling/:pageId'
            if (approveFrameUrl.startsWith('/anvil-code-low-common')) {
              const pageIdIndex = approveFrameUrl.lastIndexOf('/');
              const pageId = approveFrameUrl.substring(pageIdIndex + 1);
              const filling = approveFrameUrl.substring(0, pageIdIndex);
              this.approveObjectClone.pageId = pageId;
              const module = await import(`/@/platform/code/components${filling}.vue`);
              this.approveIframePage = module.default;
            } else {
              const module = await import(`/@/views${approveFrameUrl}.vue`);
              this.approveIframePage = module.default;
            }
          }
        }
        // 获取按钮列表
        if (this.approveObjectClone.taskId) {
          getWfButton(this.approveObjectClone.taskId).then((response) => {
            this.buttons = response.data;
          });
        }
      }
    },
    // 按钮重命名
    buttonRename(button) {
      var newName = undefined;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_BUTTON_RENAME === 'function') {
        newName = this.$refs.approveIFrame.__WF_APPROVE_FRAME_BUTTON_RENAME(button);
      }
      return newName || button.name;
    },
    // 打开窗口
    open(params) {
      this.selectUserParam = params;
      this.selectUserOpen = true;
    },
    // 关闭
    close(event, params) {
      this.initData();
      this.$emit('close', event, params);
    },
    // 选中用户
    doSelected(candidates) {
      this.selectUserOpen = false;

      var params = (this.selectUserParam && this.selectUserParam.params) || {};
      params.candidates = candidates.join(',');

      const taskId = this.selectUserParam.taskId;
      const wfWithModel = this.selectUserParam.params.wfWithModel;

      // 有taskId表示是完成待办，否则为启动工作流
      if (taskId !== null && taskId !== undefined && taskId !== '') {
        const isApprove = this.selectUserParam.isApprove;
        const approveComment = this.selectUserParam.approveComment;
        // 如果带模型，则走模型方法
        if (wfWithModel === 'Y'){
          if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_WITH_MODEL_COMPLETE_TASK === 'function') {
            this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_WITH_MODEL_COMPLETE_TASK(this, taskId, isApprove, approveComment, this.ccUserId,params);
          } else {
            this.wfClient.updateAndCompleteTask(this, taskId, isApprove, approveComment, this.ccUserId, params);
          }
        }else{
          if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_COMPLETE_TASK === 'function') {
            this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_COMPLETE_TASK(this, taskId, isApprove, approveComment, this.ccUserId,params);
          } else {
            this.wfClient.completeTask(this, taskId, isApprove, approveComment, this.ccUserId, params);
          }
        }
      } else {
        const wfCode = this.selectUserParam.wfCode;
        const businessKey = this.selectUserParam.businessKey;
        const businessSubject = this.selectUserParam.businessSubject;
        if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_START_WF_INSTANCE === 'function') {
          this.$refs.approveIFrame.__WF_INTERCEPT_SELECT_WF_NEXT_USER_START_WF_INSTANCE(this, wfCode, businessKey, businessSubject, params);
        } else {
          this.wfClient.startWfInstance(this, wfCode, businessKey, businessSubject, params);
        }
      }
    },
    //所有按钮分发事件
    handle(event, taskId) {
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_HANDLE_INTERCEPT(event, taskId, this.doHandler);
      } else {
        const formData = this.getCodeFormData();
        let originalCandidate = this.approveObjectClone.originalCandidate
        originalCandidate = originalCandidate != null ? originalCandidate.userId : ""
        this.doHandler(event, taskId, { businessSubject: this.approveObjectClone.businessSubject, originalCandidate: originalCandidate, ...formData }, null);
      }
    },

    /**
     * 默认按钮分发事件
     *
     * @param event 事件名称
     * @param taskId 待办ID
     * @param params 传入参数(业务参数，流程相关参数通过approveObject获取)
     * @param callbackFunc 回调函数
     */
    doHandler(event, taskId, params, callbackFunc) {
      params = params || {};
      // 删除不使用的对象
      params && delete params.starter;
      // 拉平多余的params
      if (params.params) {
        var tmp = params.params;
        delete params.params;
        params = { ...params, ...tmp };
      }
      if (typeof this[event] === 'function') {
        this[event](taskId, params, callbackFunc);
      } else {
        // 事件名称不是平台预置的，判断名称是否为自定义函数名
        if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame['__WF_APPROVE_FRAME_' + event + '_HANDLE_INTERCEPT'] === 'function') {
          this.$refs.approveIFrame['__WF_APPROVE_FRAME_' + event + '_HANDLE_INTERCEPT'](event, taskId, params, this.close);
        } else {
          // 如果函数名格式错误则提示警告
          if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame[event] === 'function') {
            console.warn('自定义按钮事件不合法，将忽略。函数名格式为："__WF_APPROVE_FRAME_"+event+"_HANDLE_INTERCEPT"');
          }
          this.$message.error('按钮事件处理句柄[' + event + ']不存在或定义错误，请联系管理员');
        }
      }
    },

    /**
     * 关闭按钮事件
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    closeHandler(taskId, params, callbackFunc) {
      params = params || {};
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_CLOSE_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_CLOSE_HANDLE_INTERCEPT(taskId, params, callbackFunc, this.doCloseHandler);
      } else {
        this.doCloseHandler(taskId, params, callbackFunc);
      }
    },

    /**
     * 默认关闭按钮处理方法
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    doCloseHandler(taskId, params, callbackFunc) {
      params = params || {};
      this.close('closeHandler', params);
      if (typeof callbackFunc === 'function') {
        callbackFunc({ taskId, params });
      }
    },

    /**
     * 通过按钮
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    passHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_HANDLE_INTERCEPT(taskId, approveComment, this.ccUserId, params, callbackFunc, this.doPassHandler);
      } else {
        this.doPassHandler(taskId, approveComment,  params, callbackFunc);
      }
    },

    /**
     * 发起通过请求
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doPassHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      this.wfClient.completeTask(this, taskId, 'true', approveComment, this.ccUserId, params, (response) => {
        this.close('passHandler', params);
        if (typeof callbackFunc === 'function') {
          callbackFunc({ taskId, params, response });
        }
      });
    },

    /**
     * 通过并选择下一步处理人按钮
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    passAndNextHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_AND_NEXT_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_AND_NEXT_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doPassAndNextHandler);
      } else {
        // 弹窗选择审批人
        this.doPassAndNextHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 弹窗选择审批人
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doPassAndNextHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      // this.wfClient.completeTaskAndSelectUser(this, taskId, "true", approveComment, params, callbackFunc);
      this.wfClient.completeTaskAndSelectUser(this, taskId, 'true', approveComment, this.ccUserId, params, (dest) => {
        this.open(dest);
        if (typeof callbackFunc === 'function') {
          callbackFunc(dest);
        }
      });
    },

    /**
     * 通过按钮（带模型能力）
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    passWithModelHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_WITH_MODEL_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_WITH_MODEL_HANDLE_INTERCEPT(taskId, approveComment, this.ccUserId, params, callbackFunc, this.doPassWithModelHandler);
      } else {
        this.doPassWithModelHandler(taskId, approveComment,  params, callbackFunc);
      }
    },

    /**
     * 发起通过请求（带模型能力）
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doPassWithModelHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      this.wfClient.updateAndCompleteTask(this, taskId, 'true', approveComment, this.ccUserId, params, (response) => {
        this.close('passWithModelHandler', params);
        if (typeof callbackFunc === 'function') {
          callbackFunc({ taskId, params, response });
        }
      });
    },

    /**
     * 通过并选择下一步处理人按钮（带模型能力）
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    passWithModelAndNextHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_WITH_MODEL_AND_NEXT_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_PASS_WITH_MODEL_AND_NEXT_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doPassWithModelAndNextHandler);
      } else {
        // 弹窗选择审批人
        this.doPassWithModelAndNextHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 弹窗选择审批人（带模型能力）
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doPassWithModelAndNextHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      // this.wfClient.updateAndCompleteTaskAndSelectUser(this, taskId, "true", approveComment, params, callbackFunc);
      this.wfClient.updateAndCompleteTaskAndSelectUser(this, taskId, 'true', approveComment, this.ccUserId, params, (dest) => {
        this.open(dest);
        if (typeof callbackFunc === 'function') {
          callbackFunc(dest);
        }
      });
    },

    /**
     * 驳回按钮
     *
     * @param taskId 待办ID
     * @param params 传入参数
     * @param callbackFunc 回调函数
     */
    rejectHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;

      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doRejectHandler);
      } else {
        this.doRejectHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 发起驳回(作废)请求
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doRejectHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      this.wfClient.completeTask(this, taskId, 'false', approveComment, this.ccUserId, params, (response) => {
        this.close('rejectHandler', params);
        if (typeof callbackFunc === 'function') {
          callbackFunc({ taskId, params, response });
        }
      });
    },

    /**
     * 驳回并选择下一步处理人按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    rejectAndNextHandler(taskId, params, callbackFunc) {
      params = params || {};
      //tangwei 20200416 添加驳回默认是原来的处理人
      params.defaultRejectUser = '1';
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_AND_NEXT_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_AND_NEXT_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doRejectAndNextHandler);
      } else {
        // 弹窗选择驳回者
        this.doRejectAndNextHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 弹窗选择驳回者
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doRejectAndNextHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      this.wfClient.completeTaskAndSelectUser(this, taskId, 'false', approveComment, this.ccUserId, params, (dest) => {
        this.open(dest);
        if (typeof callbackFunc === 'function') {
          callbackFunc(dest);
        }
      });
    },

    /**
     * 驳回发起人按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    rejectToStarterHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;

      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_TO_STARTER_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJECT_TO_STARTER_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doRejectToStarterHandler);
      } else {
        this.doRejectToStarterHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 驳回发起人按钮
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doRejectToStarterHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      this.wfClient.rejectToStarter(this, taskId, approveComment, this.ccUserId, params, (response) => {
        this.close('rejectToStarterHandler', params);
        if (typeof callbackFunc === 'function') {
          callbackFunc({ taskId, params, response });
        }
      });
    },

    /**
     * 废弃按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    discardHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_DISCARD_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_DISCARD_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doDiscardHandler);
      } else {
        this.doDiscardHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 废弃按钮
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见（废弃理由）
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doDiscardHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};
      console.warn('当前版本废弃功能未实现，可拦截事件后自己处理');
      if (typeof callbackFunc === 'function') {
        callbackFunc({ taskId, approveComment, params });
      }
    },

    // 如果是低代码接管的页面，获取表单值放入params参数中
    getCodeFormData() {
      try {
        const { pageId } = this.approveObjectClone;
        if (pageId) {
          const { getInstance } = this.useAnvilCodeStore();
          // 默认将表单字段带入查询接口
          return getInstance(pageId, 'form', pageId).getFormData();
        } else {
          return {};
        }
      } catch (e) {
        console.log('error!', e);
        return {};
      }
    },

    /**
     * 签入按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    claimHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_CLAIM_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_CLAIM_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doClaimHandler);
      } else {
        this.doClaimHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 签入按钮
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见（签入理由）
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doClaimHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};

      this.$confirm('签入任务后其他共同处理人将不可处理，仅自己可以处理，是否确认签入？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.wfClient.claimTask(this, taskId, approveComment, params, (response) => {
            this.close('claimHandler', params);
            if (typeof callbackFunc === 'function') {
              callbackFunc({ taskId, approveComment, params, response });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消签入'
          });
        });
    },

    /**
     * 签出按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    unClaimHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_UNCLAIM_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_UNCLAIM_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doUnClaimHandler);
      } else {
        this.doUnClaimHandler(taskId, approveComment, params, callbackFunc);
      }
    },

    /**
     * 签出按钮
     *
     * @param taskId 待办ID
     * @param approveComment 审批意见（签出理由）
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doUnClaimHandler(taskId, approveComment, params, callbackFunc) {
      params = params || {};

      this.$confirm('签出任务后其他共同处理人将有权进行处理，是否确认签出？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.wfClient.unClaimTask(this, taskId, approveComment, params, (response) => {
            this.$message.success('签出成功!');
            this.close('unClaimHandler', params);
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消签出'
          });
        });
    },

    /**
     * 转办按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    transferHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_TRANSFER_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_TRANSFER_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doTransferHandler);
      } else {
        this.doTransferHandler(taskId, approveComment, params);
      }
    },

    /**
     * 转办按钮
     * @param taskId 待办ID
     * @param approveComment 审批意见（转办理由）
     * @param params 流程参数
     */
    doTransferHandler(taskId, approveComment, params) {
      params = params || {};

      this.selectUserParam = {
        params: params,
        taskId: taskId,
        approveComment: approveComment,
        isTransfer: true
      };

      this.$refs.orgPicker.show();
    },

    /**
     * 前加签按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    addBeforeHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_ADD_BEFORE_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_ADD_BEFORE_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doTransferHandler);
      } else {
        this.doAddBeforeHandler(taskId, approveComment, params);
      }
    },

    /**
     * 前加签按钮
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doAddBeforeHandler(taskId, approveComment, params) {
      params = params || {};

      this.selectUserParam = {
        params: params,
        taskId: taskId,
        approveComment: approveComment,
        isTransfer: false,
        isAddBeforeTask: true
      };

      this.$refs.orgPicker.show();
    },

    /**
     * 后加签按钮
     *
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    addAfterHandler(taskId, params, callbackFunc) {
      params = params || {};
      var approveComment = this.approveContent;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_ADD_AFTER_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_ADD_AFTER_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doTransferHandler);
      } else {
        this.doAddAfterHandler(taskId, approveComment, params);
      }
    },

    /**
     * 后加签按钮
     * @param taskId 待办ID
     * @param params 流程参数
     * @param callbackFunc 回调函数
     */
    doAddAfterHandler(taskId, approveComment, params) {
      params = params || {};

      this.selectUserParam = {
        params: params,
        taskId: taskId,
        approveComment: approveComment,
        isTransfer: false,
        isAddBeforeTask: false,
        isAddAfterTask: true
      };

      this.$refs.orgPicker.show();
    },

    /**
     * 驳回到指定节点
     * @param taskId
     * @param params
     * @param callbackFunc
     */
    rejectedTaskTargetHandler(taskId, params, callbackFunc) {
      this.rejectedNodeParam = params || {};
      this.taskId = taskId;
      if (this.$refs.approveIFrame && typeof this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJCET_TO_START_HANDLE_INTERCEPT === 'function') {
        this.$refs.approveIFrame.__WF_APPROVE_FRAME_REJCET_TO_START_HANDLE_INTERCEPT(taskId, approveComment, params, callbackFunc, this.doTransferHandler);
      } else {
        getRejectedEnableNodes(taskId).then((response) => {
          if (response.code == '200') {
            this.rejectedNodesOpen = true
            this.rejectedNodeList = response.data;
          }
        });
      }
    },

    /**
    * 抄送
    */
    handleSelectCCUser(){
      this.selectUserParam = {
        isTransfer: false,
        isAddBeforeTask: false,
        isAddAfterTask: false,
        isCC: true
      };
      this.$refs.orgPicker.show();
    },

    /**
     * 全局选择用户并处理：前加签、后加签、转办
     *
     * @param users 目标用户id
     */
    doSelectedOrg(users) {
      const targetUserId = users
        .map((user) => {
          return user.userId;
        })
        .join(',');
      const { taskId, approveComment, params, isTransfer, isAddBeforeTask, isAddAfterTask, isCC } = this.selectUserParam;

      //抄送
      if (isCC){
        this.ccUserId = targetUserId
      }

      // 转办
      if (isTransfer) {
        this.wfClient.transferTask(this, taskId, approveComment, targetUserId, this.ccUserId, params).then(() => {
          this.close('transferHandler', params);
          this.selectUserParam = {};
          this.ccUserId = '';
        });
      }

      // 前加签
      if (isAddBeforeTask) {
        this.wfClient.addBeforeTask(this, taskId, approveComment, targetUserId, this.ccUserId, params).then(() => {
          this.close('addBeforeTaskHandler', params);
          this.selectUserParam = {};
          this.ccUserId = '';
        });
      }

      // 后加签
      if (isAddAfterTask) {
        this.wfClient.addAfterTask(this, taskId, approveComment, targetUserId, this.ccUserId, params).then(() => {
          this.close('addAfterTaskHandler', params);
          this.selectUserParam = {};
          this.ccUserId = '';
        });
      }
    },

    // 关闭驳回节点选择弹窗
    closeNodeSelectDialog() {
      this.rejectedNodesOpen = false;
    },

    // 处理已选择的节点
    handleSelectedNode(node) {
      this.rejectedNode = node;
    },

    // 驳回到指定节点
    confirmSelection() {
      const isApprove = false;
      const params = this.rejectedNodeParam || {};
      const approveComment = this.approveContent;
      this.wfClient.rejectedTaskTarget(this, this.taskId, isApprove, approveComment, this.rejectedNode, this.ccUserId, params).then(() => {
        this.close('rejectedTaskTargetHandler', params);
        this.rejectedNodeList = {};
        this.taskId = '';
        this.ccUserId = '';
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.empty {
  margin-top: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>
